<?php
use think\facade\Db;
function sp_testwrite($d) {
    $tfile = "_test.txt";
    $fp = @fopen($d . "/" . $tfile, "w");
    if (!$fp) {
        return false;
    }
    fclose($fp);
    $rs = @unlink($d . "/" . $tfile);
    if ($rs) {
        return true;
    }
    return false;
}

function sp_dir_create($path, $mode = 0777) {
    if (is_dir($path))
        return true;
    $ftp_enable = 0;
    $path = sp_dir_path($path);
    $temp = explode('/', $path);
    $cur_dir = '';
    $max = count($temp) - 1;
    for ($i = 0; $i < $max; $i++) {
        $cur_dir .= $temp[$i] . '/';
        if (@is_dir($cur_dir))
            continue;
        @mkdir($cur_dir, 0777, true);
        @chmod($cur_dir, 0777);
    }
    return is_dir($path);
}

function sp_dir_path($path) {
    $path = str_replace('\\', '/', $path);
    if (substr($path, -1) != '/')
        $path = $path . '/';
    return $path;
}

function sp_execute_sql($db,$file,$tablepre){
    //读取SQL文件
    $sql = file_get_contents(app_path() . 'data/'.$file);
    $sql = str_replace("\r", "\n", $sql);
    //替换存储类型
    $query=$db->query("show variables like '%storage_engine%'");
    $engine=$query->fetchAll();
    $engine=array_change_key_case($engine[0],CASE_LOWER);
    $engine=$engine['value'];    
    $sql=preg_replace("/(?i)ENGINE=([a-zA-Z])+ /", "ENGINE=".$engine." ", $sql);
    //
    $sql = explode(";\n", $sql);
    //替换表前缀
    $default_tablepre = "db_";
    $sql = str_replace(" `{$default_tablepre}", " `{$tablepre}", $sql);
    //开始安装
    sp_show_msg('开始安装数据库...');
    foreach ($sql as $item) {
        $item = trim($item);
        if(empty($item)) continue;
        preg_match('/CREATE TABLE `([^ ]*)`/', $item, $matches);
        if($matches) {
            $table_name = $matches[1];
            $msg  = "创建数据表{$table_name}";
            if(false !== $db->query($item)){
                sp_show_msg($msg . ' 完成');
            } else {
                sp_show_msg($msg . ' 失败！', 'error');
            }
        } else {
            $db->query($item);
        }
    
    }
}

/**
 * 显示提示信息
 * @param  string $msg 提示信息
 */
function sp_show_msg($msg, $class = ''){
    echo "<script type=\"text/javascript\">showmsg(\"{$msg}\", \"{$class}\")</script>";
    ob_flush();
    flush();    
}

function sp_update_site_configs($post){
    $data=array();
    $data["sitename"]=$post['sitename'];
    $data["pagetitle"]=$post['sitename'];
    $data["keywords"]=$post['sitekeywords'];
    $data["description"]=$post['siteinfo'];
    $data["description_len"]=200;
    $settingstr="<?php \n return ".var_export($data,true).";";//配置文件str
    $setting_path=config_path()."extra/setting.php";//配置文件路径
    file_put_contents($setting_path,$settingstr);//保存到配置文件里  
    sp_show_msg("网站信息配置成功!");
}

function sp_create_admin_account($db,$table_prefix,$data){
    $salt=make_random();
    $username=$data['manager'];
    $password=md6($data['manager_ckpwd'],$salt);    
    $sql ="replace INTO `{$table_prefix}user` (user_id,username,password,status,salt) VALUES  ('1', '{$username}', '{$password}', '1', '{$salt}');";
    $db->query($sql);
    sp_show_msg("管理员账号创建成功!");
}


/**
 * 写入配置文件
 * @param  array $config 配置信息
 */
function sp_create_config($data){
    $dbhost=$data['dbhost'];
    $dbname=$data['dbname'];
    $dbuser=$data['dbuser'];
    $dbpw=$data['dbpw'];
    $dbprefix=$data['dbprefix'];
    $envStr=";数据库的配置项
database_type='mysql'
database_hostname={$dbhost}
database_database={$dbname}
database_username={$dbuser}
database_password={$dbpw}

database_charset=utf8mb4
database_prefix={$dbprefix}
database_debug=true

APP_DEBUG =  true";
    //写入应用配置文件
    if(file_put_contents(root_path().".env", $envStr)){
        sp_show_msg('配置文件写入成功');
    } else {
        sp_show_msg('配置文件写入失败！', 'error');
    }
}
/**
 * 返回带协议的域名
 */
function sp_get_host(){
	$host=$_SERVER["HTTP_HOST"];
	$protocol=is_ssl()?"https://":"http://";
	return $protocol.$host;
}
/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl() {
    if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
        return true;
    }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
        return true;
    }
    return false;
}
/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function sp_random_string($len = 6) {
	$chars = array(
			"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
			"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
			"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
			"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
			"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
			"3", "4", "5", "6", "7", "8", "9"
	);
	$charsLen = count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output = "";
	for ($i = 0; $i < $len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;
}

